(function() {
	var $, animationStyle, chromeTabs, defaultNewTabData, tabTemplate, iframeHeight;

	$ = jQuery;

	$('.chrome-tabs-shell').addClass('cssmasks');

	tabsDefalut = '<div class="chrome-tabs"> \n <div class="chrome-tab chrome-tab-temp"> </div>  \n </div>';
	tabTemplate = '<div class="chrome-tab">\n  <div class="chrome-tab-favicon"><span class="fa"></span></div>\n	<div class="chrome-tab-title"></div>\n  <div class="chrome-tab-close"></div>\n	</div>';

	contentsDefalut = '<div class="chrome-contents"> </div>';
	contentTemplate = '<iframe class="chrome-content"></iframe>'

	defaultNewTabData = {
		tabId : 'New ID',
		title : 'New Tab',
		favicon : '',
		data : {}
	};

	animationStyle = document.createElement('style');

	chromeTabs = {
		init : function(options) {
			// 如果没有tabs，自动添加
			var tabs = options.$tabsShell.find('.chrome-tabs')
			if (!tabs.length) {
				options.$tabsShell.append(tabsDefalut);
			}

			// 如果没有contents，自动添加
			var contents = options.$contentsShell.find('.chrome-contents')
			if (!contents.length) {
				options.$contentsShell.append(contentsDefalut);
			}

			var render;
			$.extend(options.$tabsShell.data(), options);
			options.$tabsShell.prepend(animationStyle);
			options.$tabsShell.find('.chrome-tab').each(function() {
				return $(this).data().tabData = {
					data : {}
				};
			});
			render = function() {
				return chromeTabs.render(options.$tabsShell, options.$contentsShell);
			};
			$(window).resize(render);
			iframeHeight = options.contentHeight;
			return render();
		},
		render : function($tabsShell, $contentsShell) {
			chromeTabs.fixTabSizes($tabsShell, $contentsShell);
			chromeTabs.fixZIndexes($tabsShell);
			chromeTabs.setupEvents($tabsShell, $contentsShell);
			chromeTabs.setupSortable($tabsShell, $contentsShell);

			// 若是初始时，一个TAB都没有，移动会很不灵敏，此处移出该TAB
			$tabsShell.find('.chrome-tab-temp').each(function() {
				$(this).remove();
			});

			return $tabsShell.trigger('chromeTabRender');
		},
		setupSortable : function($tabsShell, $contentsShell) {
			var $tabs;
			$tabs = $tabsShell.find('.chrome-tabs');
			return $tabs.sortable({
				axis : 'x',
				tolerance : 'intersect',
				cancel : '.chrome-tab-close',
				start : function(e, ui) {
					ui.item.addClass('ui-sortable-draggable-item');
					$tabsShell.addClass('chrome-tabs-sorting');

					// 将占位符宽度设置成和TAB一致，否则TAB缩小到一定程度会出错
					var $placeholder = $tabsShell.find('.ui-sortable-placeholder');
					$placeholder.css({
						width : $tabsShell.find('.chrome-tab').first().css('width')
					});

					chromeTabs.setupTabClones($tabsShell, ui.item);
					chromeTabs.fixZIndexes($tabsShell);
					if (!$(ui.item).hasClass('chrome-tab-current')) {
						return $tabs.sortable('option', 'zIndex', $(ui.item).data().zIndex);
					} else {
						return $tabs.sortable('option', 'zIndex', $tabs.length + 40);
					}
				},
				stop : function(e, ui) {
					$('.ui-sortable-draggable-item').removeClass('ui-sortable-draggable-item');
					$tabsShell.removeClass('chrome-tabs-sorting');
					chromeTabs.cleanUpTabClones($tabsShell);
					return chromeTabs.setCurrentTab($tabsShell, $(ui.item), $contentsShell);
				},
				change : function(e, ui) {
					var placeholderIndex;
					placeholderIndex = ui.placeholder.index();
					if (ui.helper.index() <= placeholderIndex) {
						placeholderIndex -= 1;
					}
					return chromeTabs.animateSort($tabsShell, placeholderIndex);
				}
			});
		},
		animateSort : function($tabsShell, newPlaceholderIndex) {
			var $clone, $placeholder, delta, placeholderIndex;
			$clone = $tabsShell.find('.chrome-tabs.chrome-tabs-clone');
			$placeholder = $clone.find('.ui-sortable-placeholder');
			placeholderIndex = $placeholder.index();
			delta = newPlaceholderIndex - placeholderIndex;
			if (delta === -1) {
				if (newPlaceholderIndex - 1 < 0) {
					return $clone.prepend($placeholder);
				} else {
					return $($clone.find('.chrome-tab').get(newPlaceholderIndex - 1)).after($placeholder);
				}
			} else if (delta === 1) {
				return $($clone.find('.chrome-tab').get(newPlaceholderIndex)).after($placeholder);
			}
		},
		setupTabClones : function($tabsShell) {
			var $clone, $lastClone, $tabsContainer;
			$lastClone = $tabsShell.find('.chrome-tabs.chrome-tabs-clone');
			$tabsContainer = $tabsShell.find('.chrome-tabs').first();
			$clone = $tabsContainer.clone().addClass('chrome-tabs-clone');
			$clone.find('.ui-sortable-helper, .ui-sortable-draggable-item').remove();
			$clone.find('.chrome-tab').css('position', '');

			// 覆盖全局style.css的ui-sortable-placeholder
			var $placeholder = $clone.find('.ui-sortable-placeholder');
			$placeholder.addClass('chrome-ui-sortable-placeholder');

			if ($lastClone.length) {
				return $lastClone.replaceWith($clone);
			} else {
				return $tabsContainer.after($clone);
			}
		},
		cleanUpTabClones : function($tabsShell) {
			return $tabsShell.find('.chrome-tabs.chrome-tabs-clone').remove();
		},
		fixTabSizes : function($tabsShell, $contentsShell) {
			var $tabs, margin, width;
			$tabs = $tabsShell.find('.chrome-tab');
			margin = (parseInt($tabs.first().css('marginLeft'), 10) + parseInt($tabs.first().css('marginRight'), 10)) || 0;
			width = $tabsShell.width() - 50;
			width = (width / $tabs.length) - margin;
			width = Math.min($tabsShell.data().maxWidth, width);
			$tabs.css({
				width : width
			});
			chromeTabs.fixContentSizes($contentsShell, iframeHeight);

			return setTimeout(function() {
				return chromeTabs.setupAnimationStyles($tabsShell);
			});
		},
		fixContentSizes : function($contentsShell, height) {
			// Content高度
			var $contents, height;
			$contents = $contentsShell.find('.chrome-contents');
			$contents.css({
				height : height
			});
			iframeHeight = height;
			return $contentsShell;
		},
		setupAnimationStyles : function($tabsShell) {
			var $tabs, offsetLeft, styleHTML;
			styleHTML = '';
			offsetLeft = $tabsShell.find('.chrome-tabs').offset().left;
			$tabs = $tabsShell.find('.chrome-tabs:not(.chrome-tabs-clone) .chrome-tab');
			$tabs.each(function(i) {
				var $tab, left;
				$tab = $(this);
				left = $tab.offset().left - offsetLeft - parseInt($tabs.first().css('marginLeft'), 10);
				return styleHTML += ".chrome-tabs-clone .chrome-tab:nth-child(" + (i + 1) + ") {\n    left: " + left
						+ "px\n}";
			});
			return animationStyle.innerHTML = styleHTML;
		},
		fixZIndexes : function($tabsShell) {
			var $tabs;
			$tabs = $tabsShell.find('.chrome-tab');
			return $tabs.each(function(i) {
				var $tab, zIndex;
				$tab = $(this);
				zIndex = $tabs.length - i;
				if ($tab.hasClass('chrome-tab-current')) {
					zIndex = $tabs.length + 40;
				}
				$tab.css({
					zIndex : zIndex
				});
				return $tab.data({
					zIndex : zIndex
				});
			});
		},
		setupEvents : function($tabsShell, $contentsShell) {
			/*
			 * $tabsShell.unbind('dblclick').bind('dblclick', function() {
			 * return chromeTabs.addNewTab($tabsShell); });
			 */
			return $tabsShell.find('.chrome-tab').each(function() {
				var $tab;
				$tab = $(this);
				$tab.unbind('click').click(function() {
					return chromeTabs.setCurrentTab($tabsShell, $tab, $contentsShell);
				});
				return $tab.find('.chrome-tab-close').unbind('click').click(function() {
					return chromeTabs.closeTab($tabsShell, $tab, $contentsShell);
				});
			});
		},
		addNewTab : function($tabsShell, $contentsShell, newTabData) {
			var $newTab, tabData, $newContent;
			tabData = $.extend(true, {}, defaultNewTabData, newTabData);

			// 判断是否已经存在
			var origTab = chromeTabs.getTabByIndex($tabsShell, tabData.tabId);
			if (origTab) {
				$newTab = origTab;
			} else {
				$newTab = $(tabTemplate);
				$newContent = $(contentTemplate);
				$tabsShell.find('.chrome-tabs').append($newTab);
				$contentsShell.find('.chrome-contents').append($newContent);
				chromeTabs.updateTab($newTab, $newContent, tabData);
			}
			return chromeTabs.setCurrentTab($tabsShell, $newTab, $contentsShell);
		},
		setCurrentTab : function($tabsShell, $tab, $contentsShell) {
			if ($tabsShell.find('.chrome-tab-current').attr('tabId') == $tab.attr('tabId'))
				return;

			$tabsShell.find('.chrome-tab-current').find('.chrome-tab-title').removeClass('current');
			$tabsShell.find('.chrome-tab-current').find('.chrome-tab-favicon').removeClass('current');
			$tabsShell.find('.chrome-tab-current').removeClass('chrome-tab-current');
			$tab.addClass('chrome-tab-current');
			$tab.find('.chrome-tab-title').addClass('current');
			$tab.find('.chrome-tab-favicon').addClass('current');

			// 设置content当前页
			$contentsShell.find('.chrome-content-current').removeClass('chrome-content-current');
			$contentsShell.find('.chrome-content').each(function() {
				if ($(this).attr('tabId') == $tab.attr('tabId')) {
					$(this).addClass('chrome-content-current');
				}
			});
			return chromeTabs.render($tabsShell, $contentsShell);
		},
		closeTab : function($tabsShell, $tab, $contentsShell) {
			if ($tab.hasClass('chrome-tab-current')) {
				if ($tab.prev().length) {
					chromeTabs.setCurrentTab($tabsShell, $tab.prev(), $contentsShell);
				} else if ($tab.next().length) {
					chromeTabs.setCurrentTab($tabsShell, $tab.next(), $contentsShell);
				}
			}
			$tab.remove();

			// 移出content
			$contentsShell.find('.chrome-content').each(function() {
				if ($(this).attr('tabId') == $tab.attr('tabId')) {
					$(this).remove();
				}
			});

			return chromeTabs.render($tabsShell, $contentsShell);
		},
		updateTab : function($tab, $content, tabData) {
			$tab.find('.chrome-tab-title').html(tabData.title);
			if (tabData.favicon && typeof (tabData.favicon) != "undefined" && tabData.favicon != "undefined") {
				$tab.find('.chrome-tab-favicon').find('.fa').addClass(tabData.favicon);
			} else {
				$tab.find('.chrome-tab-favicon').find('.fa').addClass('fa-ban');
			}
			$tab.attr('tabId', tabData.tabId);
			$content.attr('tabId', tabData.tabId);
			$content.attr('src', tabData.url);
			return $tab.data().tabData = tabData;
		},
		getTabByIndex : function($tabsShell, tabId) {
			if (typeof tabId == 'string') {
				var tabs = $tabsShell.find('.chrome-tab');
				for (var i = 0; i < tabs.length; i++) {
					if (tabId == $(tabs[i]).attr('tabId')) {
						return $(tabs[i]);
					}
				}
			}
			return null;
		},
	};

	window.chromeTabs = chromeTabs;

}).call(this);
